const express = require("express")
const path = require("path")
const fs = require("fs")
// 处理上传文件的中间件
const formidableMiddleware = require("express-formidable")
const advModel = require("../db/model/advModel")
const adminModel = require("../db/model/adminModel")
const jwt = require("../utils/jwt")

const router = express.Router()
// 创建处理formdata的中间件函数
const middleWare = formidableMiddleware({
  // 上传的文件存储的路径
  uploadDir: "./public/uploadDir",
  // 上传的文件保留后缀名
  keepExtensions: true,
})

//自定义添加、获取、修改、删除广告时验证token的中间件
const verifyTokenMiddleWare = async function (req, res, next) {
  const authorization = req.get("authorization")
  if (authorization) {
    const admin = await adminModel.findOne({ token: authorization })
    if (admin) {
      const result = jwt.decode(authorization)
      if (Date.now() < result.expires) {
        next()
        return
      }
    }
  }
  res.send({ success: false, msg: "token无效" })
}

// 使用处理formdata的中间件函数. 这样使用,则只有当浏览器给服务器请求/addAdv路由的时候,这个中间件才会执行
router.post("/addAdv", middleWare, verifyTokenMiddleWare, async (req, res) => {
  const { advTitle, advCategory, advLink } = req.fields
  // 数据库中存储的应该是访问文件的url地址

  const filename = req.files.file.path.split("\\")[2]
  const advAvatar = `http://localhost:5001/uploadDir/${filename}`

  // 将添加的广告信息存储到数据库中
  try {
    await advModel.create({ advTitle, advCategory, advLink, advAvatar })
    res.send({ success: true, msg: "广告添加成功" })
  } catch (error) {
    res.send({ success: false, msg: "广告添加失败" })
  }
})

router.get("/findAdvs", verifyTokenMiddleWare, async (req, res) => {
  try {
    const result = await advModel.find()
    res.send({ success: true, msg: "广告数据获取成功", data: result })
  } catch (err) {
    res.send({ success: false, msg: "广告数据获取失败" })
  }
})

//删除一条广告数据的接口
router.post("/deleteAdv", verifyTokenMiddleWare, async (req, res) => {
  try {
    const { id } = req.body
    const adv = await advModel.findOne({ _id: id })
    const filename = adv.advAvatar.replace(
      "http://localhost:5001/uploadDir/",
      ""
    )
    await advModel.deleteOne({ _id: id })
    fs.unlinkSync(path.resolve(__dirname, "../public/uploadDir", filename))
    res.send({ success: true, msg: "广告数据删除成功" })
  } catch (err) {
    res.send({ success: false, msg: "广告数据删除失败" })
  }
})

router.get("/findOneAdv", async (req, res) => {
  try {
    const { id } = req.query
    const adv = await advModel.findOne({ _id: id })
    res.send({ success: true, msg: "广告数据删除成功", adv })
  } catch (err) {
    res.send({ success: false, msg: "广告数据删除失败" })
  }
})

//修改广告数据的接口
router.post(
  "/updateAdv",
  middleWare,
  verifyTokenMiddleWare,
  async (req, res) => {
    const { advTitle, advCategory, advLink, id } = req.fields
    const { file } = req.files
    if (file.size) {
      //修改了图片
      const filename = file.path.split("\\")[2]
      const advAvatar = `http://localhost:5001/uploadDir/${filename}`
      
      const adv = await advModel.findOne({ _id: id })
      
      const oldFilename = adv.advAvatar.replace(
        "http://localhost:5001/uploadDir/",
        ""
      )
      try{
        fs.unlinkSync(path.resolve(__dirname, "../public/uploadDir", oldFilename))
      }catch(err){
      }
      await advModel.updateOne(
        { _id: id },
        {
          $set: {
            advTitle,
            advCategory,
            advLink,
            advAvatar,
            advMotifyDate: Date.now(),
          },
        }
      )
      res.send({ success: true, msg: "广告修改成功" })
    } else {
      //没有修改图片
      const filename = file.path.split("\\")[2]
      fs.unlinkSync(path.resolve(__dirname, "../public/uploadDir", filename))
      await advModel.updateOne(
        { _id: id },
        {
          $set: { advTitle, advCategory, advLink, advMotifyDate: Date.now() },
        }
      )
      res.send({ success: true, msg: "广告修改成功" })
    }
    res.send({ success: false, msg: "广告修改失败" })
  }
)

module.exports = router
